import pymysql
import traceback
from DBUtils.PooledDB import PooledDB


#使用连接池操作MySql插入数据
class MySqlOperate:
    def __init__(self, maxconnections, mincached, maxcached, maxusage, host, port, user, passwd, db, charset):
        self.maxconnections = maxconnections
        self.mincached = mincached
        self.maxcached = maxcached
        self.maxusage = maxusage
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        self.charset = charset
        self.pool = self.__create_pool()

    def __create_pool(self):
        """
        创建数据库连接池
        :return: 连接池
        """
        pool = PooledDB(creator=pymysql,
                        maxconnections=self.maxconnections,  # 连接池允许的最大连接数，0和None表示不限制连接数
                        mincached=self.mincached,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
                        maxcached=self.maxcached,  # 链接池中最多闲置的链接，0和None不限制
                        maxusage=self.maxusage,  # 一个链接最多被重复使用的次数，None表示无限制
                        blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
                        host=self.host,  # 此处必须是是127.0.0.1
                        port=self.port,
                        user=self.user,
                        passwd=self.passwd,
                        db=self.db,
                        use_unicode=True,
                        charset=self.charset)
        return pool

    def save_mysql(self, sql, args):
        """
        保存数据库
        :param sql: 执行sql语句
        :param args: 添加的sql语句的参数
        :return:
        """
        try:
            db = self.pool.connection()     #连接数据库
            cursor = db.cursor()            #获取游标
            cursor.executemany(sql, args)
            db.commit()
            cursor.close()
            db.close()
        except:
            traceback.print_exc()


#测试代码
if __name__ == '__main__':
    mysql = MySqlOperate()
    sql = "insert into book (name, auth, score, download, brief, pic) values (%s, %s, %s, %s, %s, %s)"
    a = [('我的天', 'zzs', 10, 'www.baidu.com', '好看', 'zheng'), ('我的地', 'zzx', 10, 'www.google.com', '真好看', 'sheng')]
    mysql.save_mysql(sql, a)
